﻿(function () {
    var appPort = angular.module("portModule", ["basicFunctions","dateValidation"]);

    appPort.controller('PortCtrl', function ($scope, $filter, Services, $http) {

        $scope.init = function (data, type, id) {
            if (type == 'load')
                $scope.display = 'Loading';
            else
                $scope.display = 'Discharge';
            $scope.type = type;
            $scope.flag = true;
            $scope.data = data;
            $scope.hasError = false;
            $scope.str = {
                ETA_NORTime: '',
                AATime: '',
                ETB_ATBTime: '',
                ETD_ATDTime: '',
                SldDate: ''
            };
            if (id == undefined)
                $scope.id = $scope.$parent.dataItem.Id;
            else
                $scope.id = id;
            $scope.temp = {
                selected: "",
                name: "",
                notes:"",
                ETAMarker: "",
                AAMarker: "",
                ETBMarker: "",
                ETDMarker: "",
                ETCMarker: "",
                ETA_NORTime: null,
                AATime: null,
                ETB_ATBTime: null,
                ETD_ATDTime: null,
                SldDate: null
            };
            $scope.styleUnloader = { display: 'none' };
            $scope.styleLoader = { display: 'inline-block' };
            $scope.currStyle = $scope.styleUnloader;
            $scope.length = 3;
            if ($scope.data != null) {
                if ($scope.data.length > 0) {
                    if ($scope.getParent() == undefined)
                        $scope.assignParent(0);
                    $scope.temp = {
                        selected: $scope.data[$scope.getParent()].Name,
                        name: $scope.data[$scope.getParent()].Name,
                        notes: $scope.data[$scope.getParent()].Notes,
                        ETAMarker: $scope.data[$scope.getParent()].ETAMarker,
                        AAMarker: $scope.data[$scope.getParent()].AAMarker,
                        ETBMarker: $scope.data[$scope.getParent()].ETBMarker,
                        ETDMarker: $scope.data[$scope.getParent()].ETDMarker,
                        ETCMarker: $scope.data[$scope.getParent()].ETCMarker,
                        ETA_NORTime: $scope.data[$scope.getParent()].ETA_NORTime,
                        AATime: $scope.data[$scope.getParent()].AATime,
                        ETB_ATBTime: $scope.data[$scope.getParent()].ETB_ATBTime,
                        ETD_ATDTime: $scope.data[$scope.getParent()].ETD_ATDTime,
                        SldDate: $scope.data[$scope.getParent()].SldDate
                    };
                    return;
                }
            }
            $scope.enableAll(false);
        };

        $scope.changeSelectionPort = function (keyEvent, must) {
            if (keyEvent.which == 9 && ($scope.type != 'load' || must=='must')) {
                var obj = $('#nameload' + $scope.getId());
                obj.focus();
                obj.select();
                keyEvent.preventDefault();
            }
        };

        $scope.$on('changePortDate', function () {
            if ($scope.getId() == Services.changePort.id && $scope.getParent() == 0 && $scope.type==Services.changePort.type) {
                switch (Services.changePort.name) {
                    case 'ETA_NORTime':
                        $scope.str.ETA_NORTime = Services.changePort.date;
                        break;
                    case 'AATime':
                        $scope.str.AATime = Services.changePort.date;
                        break;
                    case 'ETB_ATBTime':
                        $scope.str.ETB_ATBTime = Services.changePort.date;
                        break;
                    case 'ETD_ATDTime':
                        $scope.str.ETD_ATDTime = Services.changePort.date;
                        break;
                    case 'SldDate':
                        $scope.str.SldDate = Services.changePort.date;
                        break;
                    default: break;
                }
            }
        });

        $scope.$watch('temp.selected', function () {
            if ($scope.data != undefined) {
                if ($scope.data.length == 0) {
                    $scope.temp.ETA_NORTime = null;
                    $scope.temp.AATime = null;
                    $scope.temp.ETB_ATBTime = null;
                    $scope.temp.ETD_ATDTime = null;
                    $scope.temp.SldDate = null;
                }
                else {
                    $scope.temp.ETA_NORTime = $scope.data[$scope.getParent()].ETA_NORTime;
                    $scope.temp.AATime = $scope.data[$scope.getParent()].AATime;
                    $scope.temp.ETB_ATBTime = $scope.data[$scope.getParent()].ETB_ATBTime;
                    $scope.temp.ETD_ATDTime = $scope.data[$scope.getParent()].ETD_ATDTime;
                    $scope.temp.SldDate = $scope.data[$scope.getParent()].SldDate;
                }
            }
        });

        $scope.$on('changeName', function () {
            if ($scope.type == Services.args.type && $scope.getId() == Services.args.Id) {
                $scope.temp.selected = Services.args.selected;
                $scope.temp.name = Services.args.selected;
            }
        });

        $scope.$on('markersUpdate', function () {
            if ($scope.type == Services.markers.type && $scope.getId() == Services.markers.Id) 
                $scope.UpdateText($scope.getParent());
        });

        $scope.$on('changeDataArray', function () {
            if ($scope.type == Services.data.type && Services.data.Id == $scope.getId())
                $scope.data = Services.data.data;
        });
        
        $scope.$on('changeMarker', function () {
            if ($scope.type == Services.marker.type && Services.marker.Id == $scope.getId()) {
                switch (Services.marker.name) {
                    case "ETAMarker":
                        $scope.temp.ETAMarker = Services.marker.value;
                        break;
                    case "AAMarker":
                        $scope.temp.AAMarker = Services.marker.value;
                        break;
                    case "ETBMarker":
                        $scope.temp.ETBMarker = Services.marker.value;
                        break;
                    case "ETDMarker":
                        $scope.temp.ETDMarker = Services.marker.value;
                        break;
                    case "ETCMarker":
                        $scope.temp.ETCMarker = Services.marker.value;
                        break;
                    default: break;
                }
                $scope.changed();
            }
        });

        $scope.updateCalc = function (markers, ports) {
            Services.updateCalc({ markers: markers, type: $scope.type, Id: $scope.getId(), ports: ports });
        };

        $scope.checkName = function () {
            if ($scope.temp.name == '') {
                $scope.hasError = true;
                return false;
            }
            for (var i = 0; i < $scope.data.length; i++)
                if ($scope.data[i].Name == $scope.temp.name) {
                    $scope.hasError = true;
                    return false;
                }
            $scope.hasError = false;
            return true;
        };

        $scope.setPreviousName = function () {
            if ($scope.data.length > 0) {
                $scope.temp.name = $scope.data[$scope.getParent()].Name;
                $scope.temp.selected = $scope.data[$scope.getParent()].Name;
                $scope.hasError = false;
                Services.update({ selected: $scope.temp.selected, type: $scope.type, Id: $scope.getId() });
            }
        };

        $scope.changeSelected = function () {
            if ($scope.data.length > 0 && $scope.checkName()) {
                $scope.data[$scope.getParent()].Name = $scope.temp.name;
                $scope.temp.selected = $scope.data[$scope.getParent()].Name;
                Services.update({ selected: $scope.temp.selected, type: $scope.type, Id: $scope.getId() });
                $scope.changed();
            }
        };

        $scope.changeMarker = function (name, value) {
            Services.updateMarker({ type: $scope.type, name: name, value: value, Id: $scope.getId() });
        };

        $scope.addToChat = function (message) {
            if ($scope.data.length > 0 && message != '') {
                var name = document.getElementById('windowsUserName');
                var userName = 'No_Name';
                if (name != null)
                    userName = name.innerHTML;
                var date = new Date();
                var obj = {
                    SenderName: userName,
                    Message: message,
                    Time: date
                };
                var newArray = [];
                if ($scope.data[$scope.getParent()].Chat!=undefined)
                    newArray = $scope.data[$scope.getParent()].Chat.slice();
                newArray.push(obj);
                $scope.data[$scope.getParent()].Chat = newArray;
                $scope.changed();
            }
        };

        $scope.chatScroll = function (index) {
            if (index == $scope.data[$scope.getParent()].Chat.length - 1) 
                $("#"+'Chat' + $scope.type + $scope.getId()).animate({ scrollTop: $(document).height() }, 1);
        };

        $scope.uniqueName = function (array, name) {
            for (var i = 0; i < array.length; i++)
                if (array[i].Name == name) {
                    name += '*';
                    i = -1;
                }
            return name;
        };

        $scope.createPort = function () {
            var sequence = 1;
            if ($scope.data.length > 0)
                sequence = $scope.data[$scope.data.length - 1].Sequence + 1;
            var obj = {
                AAMarker: null,
                AATime: null,
                Chat: null,
                ETA_NORTime: null,
                ETAMarker: null,
                ETB_ATBTime: null,
                ETBMarker: null,
                ETCMarker: null,
                ETD_ATDTime: null,
                ETDMarker: null,
                FinalCalculationOption: 0,
                Laytime: null,
                Name: $scope.uniqueName($scope.data, '(No_Name)'),
                Notes: null,
                Sequence: sequence,
                SldDate: null,
                Zone: null
            };
            var newArray = [];
            if ($scope.data.length == 0) {
                $scope.enableAll(true);
                newArray.push(obj);
            }
            else {
                newArray = $scope.data.slice();
                newArray.push(obj);
            }
            $scope.saveParent(newArray);
            $scope.temp.selected = $scope.data[$scope.data.length - 1].Name;
            Services.changeDataArray({ data: newArray, type: $scope.type, Id: $scope.getId() });
            $scope.UpdateSelected();
            $scope.changed();
            $scope.hasError = false;
            return 0;
        };

        $scope.deletePort = function () {
            var newArray = [];
            var temp = $scope.getParent();
            var flag = false;
            for (var i = 0; i < $scope.data.length; i++) {
                if (flag)
                    $scope.data[i].Sequence--;
                if (i != temp)
                    newArray.push($scope.data[i]);
                else
                    flag = true;
            }
            $scope.saveParent(newArray);
            if (newArray.length > 0) {
                if (temp == newArray.length)
                    temp--;
                $scope.temp.selected = $scope.data[temp].Name;
            }
            else
                $scope.setAllToZero();
            Services.changeDataArray({ data: newArray, type: $scope.type, Id: $scope.getId() });
            $scope.UpdateSelected();
            $scope.changed();
            return newArray;
        };

        $scope.setAllToZero = function () {
            $scope.temp.selected = "";
            $scope.temp.name = "";
            $scope.temp.notes = "";
            $scope.temp.ETAMarker = "";
            $scope.temp.AAMarker = "";
            $scope.temp.ETBMarker = "";
            $scope.temp.ETDMarker = "";
            $scope.temp.ETCMarker = "";

            $scope.findElement("ETA_NORTime").value = "";
            $scope.findElement("AATime").value = "";
            $scope.findElement("ETB_ATBTime").value = "";
            $scope.findElement("ETD_ATDTime").value = "";
            $scope.findElement("SldDate").value = "";
            $scope.enableAll(false);
            Services.updateTotal({ type: $scope.type, Id: $scope.id, total: 0, flag: false });
        };

        $scope.enableAll = function (value) {
            if (!$('html').hasClass('k-ie11')) {
                $scope.enableDP("ETA_NORTime", value);
                $scope.enableDP("AATime", value);
                $scope.enableDP("ETB_ATBTime", value);
                $scope.enableDP("ETD_ATDTime", value);
                $scope.enableDP("SldDate", value);
                $scope.enableAC('name' + $scope.type + $scope.getId(), value);
            }
        };

        $scope.enableDP = function (name, value) {
            var dp = $("#" + $scope.type + $scope.getId()).find("#" + name).data("kendoDateTimePicker");
            if(dp!=undefined)
                dp.enable(value);
        };

        $scope.enableAC = function (name, value) {
            var ac = $("#" + $scope.type + $scope.getId()).find("#" + name).data("kendoAutoComplete");
            if (ac != undefined)
                ac.enable(value);
        };

        $scope.saveParent = function (newArray) {
            if ($scope.type == 'load') {
                $scope.$parent.dataItem.LoadingPorts = newArray;
                $scope.data = $scope.$parent.dataItem.LoadingPorts;
            }
            else {
                $scope.$parent.dataItem.DischargePorts = newArray;
                $scope.data = $scope.$parent.dataItem.DischargePorts;
            }
        };

        $scope.UpdateSelected = function () {
            if ($scope.data.length != 0) {
                if ($scope.data.length == 0)
                    return null;
                var index = 0;
                for (var i = 0; i < $scope.data.length; i++)
                    if ($scope.data[i].Name == $scope.temp.selected)
                        index = i;
                $scope.assignParent(index);
                $scope.updateDates(index);
                $scope.UpdateText(index);
            }
        };

        $scope.UpdateText = function (index) {
            if ($scope.data.length > 0) {
                $scope.temp.name = $scope.data[index].Name;
                $scope.temp.notes = $scope.data[index].Notes;
                $scope.temp.ETAMarker = $scope.data[index].ETAMarker;
                $scope.temp.AAMarker = $scope.data[index].AAMarker;
                $scope.temp.ETBMarker = $scope.data[index].ETBMarker;
                $scope.temp.ETDMarker = $scope.data[index].ETDMarker;
            }
        };

        $scope.updateDates = function (index) { 
            if ($scope.findElement("ETA_NORTime") != undefined) {
                $scope.str.ETA_NORTime = $scope.getDateTimeString($scope.data[index].ETA_NORTime);
                $scope.str.AATime = $scope.getDateTimeString($scope.data[index].AATime);
                $scope.str.ETB_ATBTime = $scope.getDateTimeString($scope.data[index].ETB_ATBTime);
                $scope.str.ETD_ATDTime = $scope.getDateTimeString($scope.data[index].ETD_ATDTime);
                $scope.str.SldDate = $scope.getDateTimeString($scope.data[index].SldDate);

                //$scope.findElement("ETA_NORTime").value = $scope.str.ETA_NORTime;
                //$scope.findElement("AATime").value = $scope.AATime;
                //$scope.findElement("ETB_ATBTime").value = $scope.ETB_ATBTime;
                //$scope.findElement("ETD_ATDTime").value = $scope.ETD_ATDTime;
                //$scope.findElement("SldDate").value = $scope.SldDate;
            }
        };

        $scope.getDateTimeString = function (value) {
            if (value === null)
                return '';
            return $filter('date')(value, 'dd.MM.yyyy HH:mm');
        };

        $scope.assignToAll = function (name, value) {
            var objs = document.getElementsByName(name);
            for (var i = 0; i < objs.length; i++)
                if (objs[i].id != 'popup') 
                    objs[i].value = value;
        };

        $scope.findElement = function (childID) {
            var obj = document.getElementById($scope.type + $scope.getId());
            if (obj != null) {
                var elms = obj.getElementsByTagName("*");
                for (var i = 0; i < elms.length; i++) {
                    if (elms[i].id === childID)
                        return elms[i];
                }
            }
            return null;
        };

        $scope.changed = function () {
            $scope.$parent.dataItem.changed = true;
        };

        $scope.getId = function () {
            return $scope.id;
        };

        $scope.assignParent = function (index) {
            if ($scope.type == 'load')
                $scope.$parent.dataItem.SelectedLoad = index;
            else
                $scope.$parent.dataItem.SelectedDisch = index;
        };

        $scope.getParent = function () {
            if ($scope.type == 'load')
                return $scope.$parent.dataItem.SelectedLoad;
            else
                return $scope.$parent.dataItem.SelectedDisch ;
        }

        $scope.decreaseSelectedValue = function () {
            if ($scope.data.length > 0) {
                var value = $scope.getParent();
                if (value != 0) {
                    var a = $scope.data[$scope.getParent()];
                    a.Sequence--;
                    $scope.data[$scope.getParent() - 1].Sequence++;
                    $scope.data[$scope.getParent()] = $scope.data[$scope.getParent() - 1];
                    $scope.data[$scope.getParent() - 1] = a;
                    $scope.assignParent(value - 1);
                    value--;
                    $scope.assignParent(value);
                }
                $scope.temp.selected = $scope.data[$scope.getParent()].Name;
                $scope.UpdateSelected();
            }
        };

        $scope.increaseSelectedValue = function () {
            if ($scope.data.length > 0) {
                var value = $scope.getParent();
                if (value != $scope.data.length - 1) {
                    var a = $scope.data[$scope.getParent()];
                    a.Sequence++;
                    $scope.data[$scope.getParent() + 1].Sequence--;
                    $scope.data[$scope.getParent()] = $scope.data[$scope.getParent() + 1];
                    $scope.data[$scope.getParent() + 1] = a;
                    $scope.assignParent(value + 1);
                }
                $scope.temp.selected = $scope.data[$scope.getParent()].Name;
                $scope.UpdateSelected();
            }
        };

        $scope.checkMarkerTime = function () {
            if ($scope.data[$scope.getParent()].ETA_NORTime != undefined) {
                var date = new Date($scope.data[$scope.getParent()].ETA_NORTime);
                if ($scope.temp.ETAMarker == 'NOR+6h' && $scope.data[$scope.getParent()].ETAMarker != 'NOR+6h') {
                    date.setHours(date.getHours() + 6);
                    $scope.data[$scope.getParent()].ETA_NORTime = date;
                    $scope.str.ETA_NORTime = $filter('date')($scope.data[$scope.getParent()].ETA_NORTime, 'dd.MM.yyyy HH:mm');
                }
                else if ($scope.temp.ETAMarker != 'NOR+6h' && $scope.data[$scope.getParent()].ETAMarker == 'NOR+6h') {
                    date.setHours(date.getHours() - 6);
                    $scope.data[$scope.getParent()].ETA_NORTime = date;
                    $scope.str.ETA_NORTime = $filter('date')($scope.data[$scope.getParent()].ETA_NORTime, 'dd.MM.yyyy HH:mm');
                }
            }
            $scope.data[$scope.getParent()].ETAMarker = $scope.temp.ETAMarker;
        };

        $scope.serviceUri = "http://efm.develop.local/api/";

        $scope.getData = function () {
            if ($scope.temp.name.length == $scope.length) {
                $scope.currStyle = $scope.styleLoader;
                $http({
                    url: $scope.serviceUri + 'fixture/' + $scope.temp.name,
                    method: "GET"
                }).success(function (data) {
                    var autocomplete = $("#name" + $scope.type + $scope.getId()).data("kendoAutoComplete");
                    if (autocomplete != null) {
                        autocomplete.setDataSource(new kendo.data.DataSource({
                            data: data
                        }));
                        autocomplete.search($scope.temp.name);
                        $scope.currStyle = $scope.styleUnloader;
                    }
                }).error(function (data) {
                    $scope.currStyle = $scope.styleUnloader;
                });
            }
            else if ($scope.temp.name.length < $scope.length) {
                var autocomplete = $("#name" + $scope.type + $scope.getId()).data("kendoAutoComplete");
                if (autocomplete != null)
                autocomplete.refresh();
            }
        };

        $scope.changeNotes = function (notes) {
            for (var i = 0; i < $scope.data.length; i++)
                $scope.data[i].Notes = notes;
        };

        $scope.autocomplete = {
            dataTextField: "Name",
            minLength: 3,
            delay: 1000,
            select: function (e) {
                Services.changeOrderDate({
                    date: this.dataItem(e.item.index()), name: 'Zone',
                    type: $scope.type, Id: $scope.id, index:$scope.getParent()
                });
            }
            //dataSource: {
            //    type: "json",
            //    serverFiltering: true,
            //    transport: {
            //        read: {
            //            url: function (options) {
            //                return $scope.serviceUri + 'fixture';
            //            },
            //            cache: true,
            //            dataType: "json"
            //        },
            //        parameterMap: function (data, type) {
            //            if (type == "read") {
            //                return { name: $scope.temp.name };
            //            }
            //        }
            //    }
            //}
        };
    });
})();